// Copyright 2022 The spiderman-bilibili Authors. All rights reserved.

// Project: spiderman-bilibili
// IDE: GoLand
// Author: caihe.fu@qq.com
// File: video_detail.go
// Date: 2022/8/22 22:44
// Description: 哔哩哔哩 - 视频详情数据

package main

import (
	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/gocolly/colly/v2"
	"github.com/gocolly/colly/v2/extensions"
	"github.com/tidwall/gjson"
)

func extractID(link string) (string, error) {
	nURL, err := url.Parse(link)
	if err != nil {
		return "", err
	}
	uPath := strings.TrimSuffix(nURL.Path, "/")
	n := strings.LastIndex(uPath, "/")
	id := uPath[n+1:]
	return id, nil
}

func spiderVideoDetail(link string) {
	bvID, err := extractID(link)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 新建一个 colly 采集器
	c := colly.NewCollector()

	// 允许重复采集
	c.AllowURLRevisit = true

	// 设置超时时间
	c.SetRequestTimeout(15 * time.Second)

	// 自动配置 referer
	extensions.Referer(c)

	// 设置随机 user-agent
	extensions.RandomUserAgent(c)

	c.OnResponse(func(resp *colly.Response) {
		bvID := gjson.GetBytes(resp.Body, "data.bvid").String()                // bvid
		aID := gjson.GetBytes(resp.Body, "data.aid").String()                  // aid
		title := gjson.GetBytes(resp.Body, "data.title").String()              // 标题
		pubdate := gjson.GetBytes(resp.Body, "data.pubdate").Int()             // 发布时间戳
		viewCount := gjson.GetBytes(resp.Body, "data.stat.view").Int()         // 播放量
		danmakuCount := gjson.GetBytes(resp.Body, "data.stat.danmaku").Int()   // 弹幕量
		commentCount := gjson.GetBytes(resp.Body, "data.stat.reply").Int()     // 评论量
		favoriteCount := gjson.GetBytes(resp.Body, "data.stat.favorite").Int() // 收藏量
		coinCount := gjson.GetBytes(resp.Body, "data.stat.coin").Int()         // 硬币量
		shareCount := gjson.GetBytes(resp.Body, "data.stat.share").Int()       // 分享量
		likeCount := gjson.GetBytes(resp.Body, "data.stat.like").Int()         // 点赞量

		releaseTime := time.Unix(pubdate, 0)
		releaseTimeTxt := ""
		if !releaseTime.IsZero() {
			releaseTimeTxt = releaseTime.Format("2006-01-02 15:04:05")
		}

		fmt.Println("bvid ->", bvID)
		fmt.Println("aid ->", aID)
		fmt.Println("title ->", title)
		fmt.Println("release_time ->", releaseTimeTxt)
		fmt.Println("view_count ->", viewCount)
		fmt.Println("danmaku_count ->", danmakuCount)
		fmt.Println("comment_count ->", commentCount)
		fmt.Println("favorite_count ->", favoriteCount)
		fmt.Println("coin_count ->", coinCount)
		fmt.Println("share_count ->", shareCount)
		fmt.Println("like_count ->", likeCount)
	})

	vLink := fmt.Sprintf("https://api.bilibili.com/x/web-interface/view?bvid=%s", bvID)
	if err := c.Visit(vLink); err != nil {
		fmt.Println(err)
	}
}
